package com.ticket.sass.admin.business.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ticket.sass.admin.business.UserBusiness;
import com.ticket.sass.admin.dto.input.user.UserListInput;
import com.ticket.sass.admin.dto.output.user.NewUserData;
import com.ticket.sass.admin.dto.output.user.UserListOutput;
import com.ticket.sass.admin.model.PageModel;
import com.ticket.sass.admin.service.impl.OrderServiceImpl;
import com.ticket.sass.admin.service.impl.UserServiceImpl;
import com.ticket.sass.admin.util.ModelUtil;
import com.ticket.sass.common.entity.tenant.UserEntity;
import lombok.AllArgsConstructor;
import org.modelmapper.TypeToken;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ywb
 * @date 2021-11-15 15:43
 */
@Service
@AllArgsConstructor
public class UserBusinessImpl implements UserBusiness {
    
    final ModelUtil modelUtil;
    final UserServiceImpl service;
    final OrderServiceImpl orderService;

    @Override
    public PageModel<UserListOutput> getUser(UserListInput input) {
        IPage<UserEntity> page = service.iPage(input);
        List<UserListOutput> outputs = modelUtil.listToList(
            page.getRecords(),
            new TypeToken<List<UserListOutput>>(){}.getType()
        );
        
        List<Long> userIds = outputs.stream().map(UserListOutput::getId).collect(Collectors.toList());
        
        Map<Long, UserListOutput.ConsumerData> orderStatsByUserIds = orderService.getOrderStatsByUserIds(userIds);
        
        outputs.forEach(o -> o.setData(orderStatsByUserIds.getOrDefault(o.getId(), new UserListOutput.ConsumerData())));
        
        return new PageModel<>(page.getTotal(), outputs);
    }
    
    @Override
    public NewUserData newUserData() {
        NewUserData newUserData = new NewUserData();
        
        // 获取过去一周每天的新增用户数据
        List<Object[]> dailyUserCounts = service.getDailyUserCountsForPastWeek();
        newUserData.setCreateData(dailyUserCounts);
        
        // 获取总用户数
        newUserData.setTotal((int) service.count());
        
        // 提取昨天和今天的新增用户数量
        LocalDate now = LocalDate.now();
        LocalDate yesterday = now.minusDays(1);
        
        for (Object[] dailyCount : dailyUserCounts) {
            LocalDate day = (LocalDate) dailyCount[0];
            int count = (int) dailyCount[1];
            
            if (day.equals(now)) {
                newUserData.setTodayCount(count);
            } else if (day.equals(yesterday)) {
                newUserData.setYesterdayCount(count);
            }
        }
        
        return newUserData;
    }

}
